<?php
if(!isset($_SESSION['_user'])){
	echo "<script>alert('Ban chua dang nhap!');location.href='index.php?act=login';</script>";
}

if(!isset($_SESSION['carts']) || count($_SESSION['carts'])==0){
	echo "<script>alert('Ban chua chon sach!');location.href='index.php?act=list_books';</script>";
}

if($_SERVER['REQUEST_METHOD'] == 'POST'){
	$suc	=	true;
	$err	=	array();
	if($_POST['name'] == ''){
		$suc	=	false;
		$err[]	=	"Ban phai nhap ten nguoi mua hang!";
	}
	
	if($_POST['address'] == ''){
		$suc	=	false;
		$err[]	=	"Ban phai nhap dia chi!";
	}
	
	if($suc){
		mysql_query("INSERT INTO don_hang(`nguoi_mua`,`dia_chi_giao_hang`,`ghi_chu`,`ma_thanh_vien`,`ngay_dat`)VALUES('".$_POST['name']."','".$_POST['address']."','".mysql_escape_string($_POST['note'])."',".intval($_SESSION['_user']['id']).",'".date('Y-m-d H:i:s')."')");
		$id_don_hang	=	mysql_insert_id();
		$carts	=	$_SESSION['carts'];
		foreach($carts as $cart){
			mysql_query("INSERT INTO chi_tiet_don_hang(id_don_hang,id_sach,so_luong,gia)VALUES(".intval($id_don_hang).",".intval($cart['id']).",".intval($cart['num']).",".intval($cart['price']).")");
		}
		unset($_SESSION['carts']);
	}
	
}
?>
<form action="" method="post">
<table>
	<tr>
		<td>&nbsp;</td>
		<td>
		<?php 
			if(isset($err)){
				echo "<ol>";
				foreach($err as $e){
					echo "<li>".$e."</li>";
				}	
				echo "</ol>";
			}
		?>	
		</td>
	</tr>
	<tr>
		<td>Nguoi mua:</td>
		<td><input name="name"/></td>
	</tr>
	<tr>
		<td>Dia chi:</td>
		<td><input name="address"/></td>
	</tr>
	<tr>
		<td>Ngay giao hang:</td>
		<td><input name="date"/></td>
	</tr>
	<tr>
		<td>Ghi chu:</td>
		<td><textarea name="note" cols="40" rows="6"></textarea></td>
	</tr>
	<tr>
		<td></td>
		<td><input type="submit" value="Submit"/></td>
	</tr>
</table>
</form>